<template>
  <el-dialog v-model="dialogVisible" title="业务类型" :width="500">
    <el-form ref="formRef" :model="form">
      <el-form-item label="资源名称：" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="资源编码：" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { addCategory, updateCategory } from '/@/api/businessResource';
import { ElMessage } from 'element-plus';

const dialogVisible = ref(false)
const id = ref('')
const type = ref('add')

const formRef = ref()
const form = reactive({
  name: '',
  code: '',
})

const openDialog = (data?:any) => {
  dialogVisible.value = true
  if (data) {
    form.name = data.name
    form.code = data.code
    id.value = data.id
    type.value = 'edit'
  } else {
    form.name = ''
    form.code = ''
    formRef.value?.resetFields()
    type.value = 'add'
  }
}

const emit = defineEmits(['success'])
const confirm = () => {
  const { name, code } = form
  const params = {
    name,
    code,
    id: type.value == 'add' ? undefined : id.value
  }
  let apiFunc = type.value == 'add' ? addCategory : updateCategory
  apiFunc(params).then(() => {
    ElMessage.success('操作成功！')
    emit('success')
    dialogVisible.value = false
  })
}

defineExpose({ openDialog })
</script>